<?php

require_once 'db/db.php';

function loginUser( $user, $pass ) {
  try {
    $db = openDbConn();

    // validate for spaces and stuff like that
    $user = $db->quote($user);
    $pass = $db->quote($pass);

    $res = $db->query("SELECT user.id AS id, user.name AS name, permGroup.perm AS perm FROM user 
                       LEFT JOIN permGroup
                         ON user.permGroup = permGroup.id
                         WHERE user.name = $user
                           AND user.pass = $pass")->fetch(PDO::FETCH_ASSOC);
    return $res;
    } catch ( PDOException $e ) {
      print "ERROR: " . $e->getMessage() . "<br />";
      die();
    }
}

// int|string -> obj
function getUser( $uidOrName ) {
  // Not sure if I agree with this function or not. Dependence on types in PHP seems open to bugs
  // maybe have getUser( $_, $byName=false )
  try {
    $db = openDbConn();
    if( is_string( $uidOrName ) ) {
      $name = $db->quote( $uidOrName );
      $user = $db->query("SELECT user.name AS name, user.mail AS email FROM user WHERE user.name = ${name};");
    } elseif( is_int( $uidOrName ) ) {
      $uid = (int)intval( $uidOrName );
      $user = $db->query("SELECT user.name AS name, user.mail AS email FROM user WHERE user.id = ${uid};");
    } else  {
      die( "BREAKAGE" ); // BREAKAGE
    }
    return $user->fetch(PDO::FETCH_ASSOC);
  } catch ( PDOException $e ) {
    print "ERROR: " . $e->getMessage() . "<br />";

    die();
  }
}

// () -> string
function getPermList( $uid ) {
  try {
    $db = openDbConn();    

    $res = $db->query("SELECT perm FROM perms WHERE id = {$uid} ORDER BY perm ASC");
    $resArr = $res->fetchAll(PDO::FETCH_COLUMN);
    $permlist = implode(',',$resArr); // can we do this with sql?
    $resArr = NULL;
    return $permlist;
  } catch ( PDOException $e ) {
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  }
}

?>
